package jprint.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import java.io.IOException;
import java.io.Reader;

/**
 * @author zw-zheng
 * Created on 2020-11-29
 */
public class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    private JsonUtil() {
    }

    public static String toJsonString(Object obj) {
        String json = null;
        try {
            json = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException ignored) {
            // ignored
        }
        return json;
    }

    public static <T> T fromJsonString(String json, Class<T> clz) {
        ObjectReader reader = mapper.readerFor(clz);
        T obj = null;
        try {
            obj = reader.readValue(json);
        } catch (JsonProcessingException e) {
            // ignored
        }
        return obj;
    }

    public static <T> T fromJsonString(Reader reader, Class<T> clz) {
        ObjectReader _reader = mapper.readerFor(clz);
        T obj = null;
        try {
            obj = _reader.readValue(reader);
        } catch (IOException ignored) {
            // ignored
        }
        return obj;
    }
}
